package com.wbpay.sdk.wrapper;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.wbpay.sdk.dlg.CancelPayDialog;
import com.wbpay.sdk.framework.PayResult;
import com.wbpay.sdk.utils.Log;
import com.wbpay.sdk.utils.Utils;

import java.util.Map;
import java.util.TreeMap;

import static android.os.Build.VERSION_CODES.M;

/**
 * 聚宝支付activity
 */
public class JubaoPayWrapper extends ActivityWrapper {

    private static final int GO_TO_ALIPAY = 1000;
    private static final long ALIPAY_DELAY_TIME = 1500L;
    private static final String ALIPAY_INTENT_URL = "intent://platformapi/startapp?saId=10000007&" +
            "clientVersion=3.7.0.0718&qrcode=https%3A%2F%2Fqr.alipay.com%2F{urlCode}%3F_s" +
            "%3Dweb-other&_t={time}#Intent;scheme=alipayqr;package=com.eg.android.AlipayGphone;end";

    // 是否已经跳转到支付宝
    private volatile boolean isGotoAlipay;

    private static final String ALIPAY_QRCODE_URL_PREFIX = "https://qr.alipay.com/";

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                // 如果两秒后没有跳转到支付宝的话，手动构造 intent 跳转
                case GO_TO_ALIPAY:
                    if (!isGotoAlipay) {
                        String urlCode = (String) msg.obj;
                        String url = ALIPAY_INTENT_URL.replace("{urlCode}", urlCode)
                                .replace("{time}", String.valueOf(System.currentTimeMillis()));
                        gotoAlipay(url);
                    }
                    break;
            }
        }
    };

    private WebView mWebView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String url = "http://106.14.185.49:8080/jubaopay/mall.jsp";
        url = configUrl(url);
        Log.d(Log.TAG, "url : " + url);
        mWebView = new WebView(getActivity());
        getActivity().setContentView(mWebView);
        mWebView.addJavascriptInterface(this, "jubaopay");
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView webView, String url) {
                Log.d(Log.TAG, "url : " + url);
                if (url.startsWith(ALIPAY_QRCODE_URL_PREFIX)) {
                    String urlCode = url.replace(ALIPAY_QRCODE_URL_PREFIX, "");
                    Message message = Message.obtain();
                    message.what = GO_TO_ALIPAY;
                    message.obj = urlCode;
                    // 如果是Android 7.0及以上，直接跳转至支付宝
                    // 否则给出一些预留时间(1.5秒)，看能否跳转
                    if (Build.VERSION.SDK_INT > M) {
                        mHandler.sendMessage(message);
                    } else {
                        mHandler.sendMessageDelayed(message, ALIPAY_DELAY_TIME);
                    }
                } else if (url.startsWith("weixin:")
                        || url.startsWith("alipayqr")
                        || url.startsWith("alipays")
                        || url.startsWith("mqqapi://")) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    try {
                        getActivity().startActivity(intent);
                    } catch (Exception e) {
                        super.shouldOverrideUrlLoading(webView, url);
                    }
                    return true;
                } else if (url.startsWith("intent://platformapi/startapp")) {
                    if (!isGotoAlipay) {
                        gotoAlipay(url);
                    }
                    return true;
                }
                return super.shouldOverrideUrlLoading(webView, url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                Log.d(Log.TAG, "url : " + url);
            }
        });
        // 加载支付 url
        mWebView.loadUrl(url);
    }

    private String configUrl(String url) {
        String tmp = null;
        Intent intent = getActivity().getIntent();
        Map<String, String> map = new TreeMap<String, String>();
        if (intent != null) {
            tmp = intent.getStringExtra("server");
            map.put("server", tmp);
            tmp = intent.getStringExtra("price");
            map.put("price", tmp);
            tmp = intent.getStringExtra("attach");
            map.put("attach", tmp);
            tmp = intent.getStringExtra("subject");
            map.put("subject", tmp);
            tmp = intent.getStringExtra("order");
            map.put("order", tmp);
            tmp = intent.getStringExtra("body");
            map.put("body", tmp);
        }
        StringBuilder builder = new StringBuilder();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (entry != null && !TextUtils.isEmpty(entry.getValue())) {
                builder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
        }
        if (builder.length() > 0) {
            builder.deleteCharAt(builder.length() - 1);
        }
        if (builder.length() > 0) {
            return url + "?" + builder.toString();
        }
        return url;
    }

    // 跳转到支付宝
    private void gotoAlipay(String url) {
        try {
            Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
            intent.addCategory("android.intent.category.BROWSABLE");
            intent.setComponent(null);
            getActivity().startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // set the flag
        isGotoAlipay = true;
    }

    @JavascriptInterface
    public void notifyWebPayResult(boolean success, String desc) {
        Utils.sendPayResult(getActivity(), success ? PayResult.PAY_SUCCESS : PayResult.PAY_FAILURE, desc, getCallbackAction());
    }

    private void notifyPayResult(int code, String desc) {
        Utils.sendPayResult(getActivity(), code, desc, getCallbackAction());
        getActivity().finish();
    }

    @Override
    public void onDestroy() {
        mHandler.removeCallbacksAndMessages(null);
        mWebView.removeAllViews();
        mWebView.destroy();
        mWebView = null;
        super.onDestroy();
    }

    @Override
    public boolean onBackPressed() {
        /**
         if (mWebView.canGoBack()) {
         mWebView.goBack();
         return true;
         }*/
        showCancelPayDialog();
        return true;
    }

    private void showCancelPayDialog() {
        CancelPayDialog cancelPayDialog = new CancelPayDialog(getActivity());
        cancelPayDialog.setOnOkClickListener(new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String desc = getActivity().getString(Utils.getStringId(getActivity(), "jy_cancel_pay"));
                notifyPayResult(PayResult.PAY_CANCEL, desc);
            }
        });
        cancelPayDialog.show();
    }
}